<template>
  <div>
    <search-bar @onSearch="searchResult" ref="searchBar"></search-bar>
    <div class="goods-container">
      <!-- 当商品列表为空时显示空占位图 -->
      <el-empty 
        v-if="books.length === 0" 
        description="暂无商品，请稍后再来看看吧~"
        :image-size="200"
      >
      </el-empty>
      
      <!-- 商品列表 -->
      <el-tooltip
        effect="light"
        placement="right"
        popper-class="custom-tooltip"
        v-for="item in books"
        :key="item.id"
        v-else
      >
        <p
          slot="content"
          style="font-size: 15px;margin-bottom: 6px;font-family: 600;"
        >
          {{ item.goodsName }}
        </p>
        <p slot="content" style="font-size: 13px;margin-bottom: 6px;">
          <span>{{ item.description }}</span>
        </p>
        <p
          slot="content"
          style="font-size: 13px;margin-bottom: 6px;color: #FF4F24;"
        >
          <span
            style="text-decoration: line-through; color: #00caa8; margin-right: 8px;"
            >￥{{ item.originalPrice }}</span
          >
          <span style="font-weight: bold;">￥{{ item.price }}</span>
        </p>
        <div class="goods-card" @click="bookDetail(item)">
          <div class="goods-img">
            <el-image :src="item.mainImage" fit="cover"></el-image>
          </div>
          <div class="goods-info">
            <div class="goods-name">{{ item.goodsName }}</div>
            <div class="price-container">
              <div class="goods-originalPrice">￥{{ item.originalPrice }}</div>
              <div class="goods-price">￥{{ item.price }}</div>
            </div>
          </div>
        </div>
      </el-tooltip>
    </div>
    <el-row>
      <el-pagination
        @current-change="handleCurrentChange"
        :current-page="currentPage"
        :page-size="pageSize"
        :total="total"
        background
      >
      </el-pagination>
    </el-row>
  </div>
</template>

<style scoped lang="scss">
.goods-container {
  width: 100%;
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(200px, 1fr));
  overflow: visible;
  margin-bottom: 20px;
  gap: 20px;
  
  // 空状态居中显示
  .el-empty {
    grid-column: 1 / -1; // 占满整行
    display: flex;
    justify-content: center;
    align-items: center;
    min-height: 400px;
  }
  
  .goods-card {
    display: flex;
    flex-direction: column;
    align-items: center;
    padding: 5%;
    border-radius: 10px;
    box-sizing: border-box;
    transition: all 0.3s ease;
    text-align: left;
    background: #fff;
    height: 100%;
    position: relative;

    .goods-img {
      width: 100%;
      padding-top: 90%;
      background-color: rgb(230, 229, 229);
      border-radius: 10px;
      position: relative;
      overflow: hidden;
      display: flex;
      align-items: center;
      justify-content: center;
      .el-image {
        position: absolute;
        top: 0;
        left: 0;
        width: 100%;
        height: 100%;
        object-fit: cover;
      }
    }

    .goods-info {
      width: 100%;
      display: flex;
      flex-direction: column;
      flex: 1;
      justify-content: space-between;
      margin-top: 10px;
    }

    .goods-name {
      width: 100%;
      font-size: 1.1em;
      font-weight: bold;
      margin-bottom: 4px;
      text-align: left;
      white-space: nowrap;
      overflow: hidden;
      text-overflow: ellipsis;
      line-height: 1.3em;
    }

    .price-container {
      width: 100%;
      margin-top: auto;
      padding: 4px 0;
    }

    .goods-originalPrice {
      width: 100%;
      color: #00caa8;
      font-size: 0.85em;
      text-align: left;
      margin-bottom: 4px;
      text-decoration: line-through;
      opacity: 0.8;
      transition: opacity 0.3s ease;
    }

    .goods-price {
      width: 100%;
      color: #ff4f24;
      font-weight: bold;
      font-size: 1.2em;
      text-align: left;
      display: block;
      transition: color 0.3s ease;
    }
  }
  .goods-card:hover {
    cursor: pointer;
    box-shadow: 0 0 10px rgba(0, 0, 0, 0.2);
  }
}
</style>

<style>
.custom-tooltip {
  background: white !important;
  border: 1px solid #00caa8 !important;
  border-radius: 8px !important;
  box-shadow: 0 4px 12px rgba(0, 202, 168, 0.2) !important;
  color: #2c3e50 !important;
}
.custom-tooltip .el-tooltip__popper {
  background: white !important;
  color: #2c3e50 !important;
}
.custom-tooltip[x-placement^="right"] .popper__arrow {
  border-right-color: #00caa8 !important;
}
.custom-tooltip[x-placement^="left"] .popper__arrow {
  border-left-color: #00caa8 !important;
}
.custom-tooltip[x-placement^="top"] .popper__arrow {
  border-top-color: #00caa8 !important;
}
.custom-tooltip[x-placement^="bottom"] .popper__arrow {
  border-bottom-color: #00caa8 !important;
}
</style>

<script>
import SearchBar from "../common/SearchBar";

export default {
  name: "books",
  components: { SearchBar },
  data() {
    return {
      keywords: "",
      minPrice: null,
      maxPrice: null,
      books: [],
      currentPage: 1,
      pageSize: 15, // 初始值
      rows: 3, // 每页显示几行
      total: 0 // 新增：用于存储总数据量
    };
  },
  mounted: function() {
    this.loadBooks(); // 启用真实接口
    // this.loadMockBooks(); // 注释掉模拟数据
    this.calcPageSize();
    window.addEventListener("resize", this.calcPageSize);
  },
  beforeDestroy() {
    window.removeEventListener("resize", this.calcPageSize);
  },
  methods: {
    loadBooks() {
      let url = "/goods/search";
      let params = {
        page: 1,
        size: this.pageSize
      };

      // 添加搜索关键词
      if (this.keywords) {
        params.keyword = this.keywords;
      }

      // 添加价格筛选
      if (this.minPrice !== null && this.minPrice !== '') {
        params.minPrice = this.minPrice;
      }
      if (this.maxPrice !== null && this.maxPrice !== '') {
        params.maxPrice = this.maxPrice;
      }

      this.$axios
        .get(url, { params })
        .then(resp => {
          if (resp && resp.status === 200) {
            // 处理MyBatis-Plus分页格式：{ data: { records: [...], total: xxx } }
            const responseData = resp.data.data;
            if (responseData && responseData.records) {
              this.books = responseData.records;
              // 更新总数用于分页
              this.total = responseData.total || 0;
            } else {
              this.books = [];
            }
          }
        })
        .catch(error => {
          console.error("获取商品列表失败:", error);
          // 如果接口失败，使用模拟数据作为备用
          this.loadMockBooks();
        });
    },
    loadMockBooks() {
      this.books = [];
    },
    searchResult(searchParams) {
      this.keywords = searchParams.keyword || '';
      this.minPrice = searchParams.minPrice;
      this.maxPrice = searchParams.maxPrice;
      this.currentPage = 1; // 重置到第一页
      this.$emit("search");
    },
    handleCurrentChange(currentPage) {
      this.currentPage = currentPage;
      // 重新请求数据
      this.loadBooksByPage(currentPage);
    },

    // 新增：根据页码加载数据
    loadBooksByPage(page) {
      let url = "/goods/search";
      let params = {
        page: page,
        size: this.pageSize
      };

      // 如果有搜索关键词，添加关键词参数
      if (this.keywords) {
        params.keyword = this.keywords;
      }

      // 添加价格筛选
      if (this.minPrice !== null && this.minPrice !== '') {
        params.minPrice = this.minPrice;
      }
      if (this.maxPrice !== null && this.maxPrice !== '') {
        params.maxPrice = this.maxPrice;
      }

      this.$axios
        .get(url, { params })
        .then(resp => {
          if (resp && resp.status === 200) {
            const responseData = resp.data.data;
            if (responseData && responseData.records) {
              this.books = responseData.records;
              this.total = responseData.total || 0;
              this.currentPage = page;
            } else {
              this.books = [];
            }
          }
        })
        .catch(error => {
          console.error("获取商品列表失败:", error);
        });
    },
    bookDetail(book) {
      this.$store.commit("setBook", book);
      this.$router.push(`/index/goodDetail/${book.id}`);
    },
    calcPageSize() {
      this.$nextTick(() => {
        const container = this.$el.querySelector(".goods-container");
        if (container) {
          // 获取真实宽度
          const containerWidth = container.getBoundingClientRect().width;
          const cardMinWidth = 200 + 20; // 200px卡片+20px gap
          const perRow = Math.max(1, Math.floor(containerWidth / cardMinWidth));
          this.pageSize = perRow * this.rows;
          this.currentPage = 1; // 自动跳到第一页，避免溢出
          console.log(
            "containerWidth:",
            containerWidth,
            "cardMinWidth:",
            cardMinWidth,
            "perRow:",
            perRow,
            "pageSize:",
            this.pageSize
          );
        }
      });
    }
  }
};
</script>
